package cms.web.util;

import cms.common.data.ApiResultCode;
import cms.common.exception.NoLoginException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by moueimei on 2017/6/10.
 */
public class WsWebSessionUtil {
    /**
     * 获取登陆签名 openId 或者 unionid
     * @return
     */
    public static String getLoginToken(HttpSession session) {
        String token = session.getId();
        return token;
    }

    public static void okLogin(HttpSession session, Long uid) {
        if( null != uid ) {
            session.setAttribute("_uid_", uid);
        }
    }

    /**
     * 检查是否登陆过
     * @param session
     */
    public static void checkLogin(HttpSession session){
        Long uid = (Long) session.getAttribute("_uid_");
        if( null == uid){
            throw new NoLoginException(ApiResultCode.NO_LOGIN_SUCCESS);
        }
    }

    /**
     * 用户用户ID
     * @param session
     * @param ckLogin
     * @return
     */
    public static Long getUid(HttpSession session, boolean ckLogin){
        if(ckLogin) {
            checkLogin(session);
        }
        return (Long) session.getAttribute("_uid_");
    }

    public static void logout(HttpSession session) {
        session.removeAttribute("_user_info_");
        session.invalidate();
    }

    /**
     * 是否是微信
     * @return
     */
    public static boolean isWx(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String url = request.getRequestURI().toString();
        return StringUtils.contains(url,"/wx/");
    }

//    public static User getUser(HttpSession session,boolean ckLogin) {
//        Long uid = getUid( session,ckLogin);
//        if(uid==null){
//            return null;
//        }
//        return (SpringContextHolder.getBean(UserService.class)).findUserById(uid);
//    }

}
